//
//  MClientAppDelegate.m
//  MClient
//
//  Created by  史正烨 on 09-9-19.
//  Copyright __MyCompanyName__ 2009. All rights reserved.
//

#import "MClientAppDelegate.h"
#import "MServerConfigCache.h"
#import "MCFunction.h"
#import "LoginController.h"
#import "MenuController.h"
#import "MServerDAO.h"
#import "MServerJsonDAO.h"
#import "MCUserDefaults.h"
#import <stdio.h>

#import "AudioToolbox/AudioToolbox.h"
#import "SettingController.h"
#import "DemoController.h"
#import "InitController.h"
#import "Sqlite3DbManager.h"
#import "MCUIToolkit.h"

#pragma mark  ---MClientAppDelegate---
static NSArray *loginInfo = nil;
static NSDictionary *infoDictionary;  //全局mainBundle字典，由getInfoDictionary为全局使用。huotianjun
static NSString *defaultServerUrl = @"http://sh1.mobile086.cn";
static NSMutableDictionary *constantDictionary;//程序私有Bundle信息，由getConstantDictionary为全局提供。huotianjun

@implementation MClientAppDelegate

@synthesize window;
@synthesize navController;
@synthesize apsOptions;
@synthesize deviceToken;

- (void)applicationDidFinishLaunching:(UIApplication *)application {    
	
    // Override point for customization after application launch
	@try {
       //yuxiaotong 2013-11-25 09:35:58
#pragma mark  ----------------add 2.13.9.24  修改适配iphone5 屏幕之后 window 的frame  解决屏幕下面不能点击的问题
        if ([[UIScreen mainScreen]bounds].size.height == 568) {
            window.frame = CGRectMake(0, 0, [[UIScreen mainScreen]bounds].size.width, [[UIScreen mainScreen]bounds].size.height);
        }

		NSBundle *mainBundle = [NSBundle mainBundle];

		//取MClient-Info.plist内的参数信息
		infoDictionary = [mainBundle infoDictionary];
		NSString *path = [[NSBundle mainBundle] pathForResource:@"MClientConstant" ofType:@"plist"];
		//取MClientConstant.plist里设置的值
		constantDictionary = [[[NSMutableDictionary alloc]initWithContentsOfFile:path] retain];
		
		[[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(applicationWillTerminate:) 
													 name:UIApplicationWillTerminateNotification 
												   object:application];
		MCUserDefaults *defaults = [MCUserDefaults instance];//分析用户默认设置。huotianjun
		defaults.current_ServerUrl = defaults.current_ServerUrl;
		
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)]; //huotianjun
        
		//defaults.isHidePartyId = NO;
#if TARGET_IPHONE_SIMULATOR
		navController = [[MCNavigationController alloc] initWithRootViewController:[[[[defaults class:@"LoginController"] alloc] init] autorelease]];
#else
		BOOL needInit = [[constantDictionary objectForKey:@"isNeedInit"] boolValue];
		if (needInit && (defaults.isFirstUse || defaults.isSetupFirst)) {
			defaults.isAutoLogin = NO;
			navController = [[MCNavigationController alloc] init];
			[navController setViewControllers:[NSArray arrayWithObjects:[[[[defaults class:@"LoginController"] alloc] init] autorelease],[[[InitController alloc] init] autorelease],nil]];
		}else {
			navController = [[MCNavigationController alloc] initWithRootViewController:[[[[defaults class:@"LoginController"] alloc] init] autorelease]];
		}
#endif
		navController.identifierId = 0;
		[window addSubview:navController.view];
		
		//	UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(25, 0, 100, 20)];
		//	label.text = @"数据请求中...";
		//	label.font = [UIFont systemFontOfSize:12];
		//	label.backgroundColor = [UIColor clearColor];
		//	activityIndicator = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(90, 164, 32, 32)];
		//	[activityIndicator addSubview:label];
		//	[label release];
		
		//activityIndicator = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(144, 164, 32, 32)];//huotianjun
		//[activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];//huotianjun
		//activityIndicator.tag = -100;//huotianjun
		
		//[window addSubview:activityIndicator];//huotianjun
        
        myActivityIndicator = [[[TTActivityLabel alloc] initWithStyle:TTActivityLabelStyleBlackBezel] autorelease];
        myActivityIndicator.text = [infoDictionary valueForKey:@"CFBundleDisplayName"]; 
        [myActivityIndicator sizeToFit];
        //myActivityIndicator.frame = CGRectMake(0, 0, window.width, window.height);
        myActivityIndicator.frame = CGRectMake(0, 60, window.width, window.height-80);
        [window addSubview:myActivityIndicator];
        [window sendSubviewToBack:myActivityIndicator];
        
		[window makeKeyAndVisible];
	}
	@catch (NSException * e) {
		[[MCErrorManagement instance] doError:@"99" returnMessage:[e reason]];
	}
    //mongooseDaemon = [[MongooseDaemon alloc] init];
    //[mongooseDaemon startMongooseDaemon:@"8080"];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
	if (!url)
		return NO;
	
	NSString *URLString = [url absoluteString];
	
	loginInfo = [[[URLString substringFromIndex:10] componentsSeparatedByString:@","] retain];
	
	return YES;
}

- (void)dealloc {
	[navController release];
	//[activityIndicator release];
    [myActivityIndicator release];
    [window release];
	[apsOptions release];
	[deviceToken release];
    
    //[mongooseDaemon stopMongooseDaemon];
    //[mongooseDaemon release];
	
    [super dealloc];
}

#pragma mark ---- 应用退出处理方法 ----

- (void)applicationWillTerminate:(UIApplication *)application {
	[[MServerConfigCache sharedInstance] saveCacheToStore];
}

//iOS4
- (void)applicationDidEnterBackground:(UIApplication *)application {
	[[MServerConfigCache sharedInstance] saveCacheToStore];
}

#pragma mark ---- 应用退出处理方法 ----

+ (NSArray *)getLoginInfo {
	return loginInfo;
}

+ (void)resetLoginInfo {
	loginInfo = nil;
}

+ (NSDictionary *)getInfoDictionary {
	return infoDictionary;
}

+ (NSString *)getDefaultServerUrl {
	if ([constantDictionary objectForKey:@"serverUrl"] == nil) {
		return defaultServerUrl;
	}
	return [[constantDictionary objectForKey:@"serverUrl"] copy];
}

+ (NSMutableDictionary *)getConstantDictionary {
	return constantDictionary;
}

- (void)startActivityIndicatorView {
	//[self.window bringSubviewToFront:activityIndicator];//huotianjun
	//[activityIndicator startAnimating];//huotianjun
    [self.window bringSubviewToFront:myActivityIndicator];
    myActivityIndicator.isAnimating = YES;
	
    
	//navController.visibleViewController.view.userInteractionEnabled = NO;
//	navController.view.userInteractionEnabled = NO;
	//navController.navigationBar.userInteractionEnabled = NO;
}

- (void)stopActivityIndicatorView {
	//[activityIndicator stopAnimating];
    [self.window sendSubviewToBack:myActivityIndicator];
    myActivityIndicator.isAnimating = NO;
    
	//navController.visibleViewController.view.userInteractionEnabled = YES;
//	navController.view.userInteractionEnabled = YES;
	//navController.navigationBar.userInteractionEnabled = YES;
}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)aDeviceToken {
    NSLog(@"deviceToken: %@", aDeviceToken); 
	
	[MCUserDefaults instance].deviceToken = [[aDeviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<> "]];
} 

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"Error in registration. Error: %@", error); 
} 

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    NSLog(@"收到推送消息 ： %@",[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]);
    if ([[userInfo objectForKey:@"aps"] objectForKey:@"alert"]!=NULL) {
		self.apsOptions = [userInfo objectForKey:@"aps"];
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"推送通知" 
                                                        message:[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]
                                                       delegate:self 
                                              cancelButtonTitle:@"关闭"
                                              otherButtonTitles:@"更新状态",nil];
        [alert show];
        [alert release];
    }
}

// 注册推送通知
- (void)registerRemotNotification {
	// 注册推送通知
	if ([MCUserDefaults instance].remoteNotification &&
		[[MCUserDefaults instance].deviceToken length] <= 0) {
		[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
	}
}

- (void)launchApplication:(UIApplication *)application {
	// 注册推送服务
	[self registerRemotNotification];
	// 启动客户端页面
	[self applicationDidFinishLaunching:application];
}

// 查看通知内容
- (void)handleRemotNotification
{
	if (nil == self.apsOptions) {
		return;
	}
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    
    // 要使用百度地图，请先启动BaiduMapManager
	_mapManager = [[BMKMapManager alloc] init];
    // 如果要关注网络及授权验证事件，请设定generalDelegate参数
	BOOL ret = [_mapManager start:@"1d701c2607b6bad57edfaf4b662c67cb" generalDelegate:nil];
	if (!ret) {
		NSLog(@"manager start failed!");
	}else{
        NSLog(@"百度地图连接成功");
    }
    
    
	MCLog(@"%@", [NSString stringWithFormat:@"application didFinishLaunchingWithOptions: %@", launchOptions]);
	// 启动客户端页面
	[self launchApplication:application];
	
	// 处理通知内容
	self.apsOptions = [launchOptions objectForKey:UIApplicationDidFinishLaunchingNotification];
	[self handleRemotNotification];
	
	return YES;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
	if (buttonIndex>0) {
		// 处理推送内容
		[self handleRemotNotification];
	}
}
@end
